<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @name Auth
 * @file auth.php
 * @author Miroslava Matúšková
 * @version 1.0
 * @package CodeIgniter
 * @subpackage Controllers
 * @section POPIS
 * Predstavuje kontroler ktorý bude zastrešovať autentifikáciu admina, zmenu hesiel, log in, log out. 
 * Je to vitálny kontroler, bez ktorého by aplikácia stratila istú úroveň funkcionality a bezpečnosti.
 */
class Auth extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model(array('AdminsModel', 'PasswordModel'));                      // používanie Admin Modelu a Password Modelu z Acicrud
    }

    /**
     * Funkcia bude sprostredkovávať prihlásenie admina do aplikácie.
     *
     * Je potrebné zadať login a password.
     */
    public function log_in() {
        $data['title'] = 'Prihlásenie';
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->form_validation->set_rules('username', 'Prihlasovacie meno', 'trim|required|xss_clean|min_length[3]|max_length[40]');
            $this->form_validation->set_rules('password', 'Heslo', 'trim|required|min_length[4]|max_length[40]');
            $accepted = false;
            if (!($this->form_validation->run() == false)) {
                $userName = $this->input->post('username');
                $userPass = $this->input->post('password');
                $userPassHashed = hash('sha1', $userPass);
                $user = $this->AdminsModel->getBy('login', $userName);
                if (!empty($user) && $user->password == $userPassHashed) {
                    $this->createSession($user);
                    $this->updateLastLogin($user->id);
                    $data['accept_message'] = 'Boli ste úspešne prihlásený!';
                    $accepted = true;
                } else {
                    $data['error_message'] = 'Nesprávne zadané prihlasovacie údaje.';
                }
            } else {
                $data['error_message'] = 'Nesprávne zadané prihlasovacie údaje. Chyba pri validácii.';
            }
        }
        if ($accepted) {
            $data['redirect_to'] = ''; // url , kde sa bude redirectovat '' home, inac napr 'programs_managment/index' inde
            $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
        } else {
            $this->load->view('templates/headers/header', $data, FALSE);
        }
        $this->load->view('auth/log_message', $data, FALSE);
        $this->load->view('templates/footers/footer', null, FALSE);
    }

    /**
     * Funkcia slúžiť na odhlásenie admina z aplikácie.
     */
    public function log_out() {
        $data['title'] = 'Odhlásenie';
        if (!$this->user->isLogged()) {
            $data['error_message'] = 'Nie ste prihlásený!';
            $data['redirect_to'] = ''; // url , kde sa bude redirectovat '' home, inac napr 'programs_managment/index' inde
            $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
            $this->load->view('auth/log_message', $data, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
            return;
        }
        $accepted = false;
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->user->unsetData();
            $data['accept_message'] = 'Boli ste úspešne odhlásený!';
            $accepted = true;
        } else
            $data['error_message'] = 'Nepodarilo sa odhlásiť.';
        if ($accepted) {
            $data['redirect_to'] = ''; // url , kde sa bude redirectovat '' home, inac napr 'programs_managment/index' inde
            $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
        } else {
            $this->load->view('templates/headers/header', $data, FALSE);
        }
        $this->load->view('auth/log_message', $data, FALSE);
        $this->load->view('templates/footers/footer', null, FALSE);
    }

    /**
     * 	Funkcia zabezpečuje zmenu hesla admina pre prihlásenie.
     * 
     * Pre zmenu hesla musí prihlasený administrátor zadať staré heslo, nové heslo a ešte raz nové heslo
     * pre kontrolu zhody hesiel. Následne sa heslo zmení.
     */
    public function pass_change() {
        if (!$this->user->isLogged()) {
            $data['error_message'] = 'Nie ste prihlásený!';
            $data['redirect_to'] = ''; // url , kde sa bude redirectovat '' home, inac napr 'programs_managment/index' inde
            $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
            $this->load->view('auth/log_message', $data, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
            return;
        }

        $data['title'] = 'Zmena hesla';
        $data['oldpass'] = array(
            'name' => 'oldpass',
            'id' => 'oldpass',
            'type' => 'password',
            'placeholder' => 'Heslo',
            'value' => $this->form_validation->set_value('password'),
        );
        $data['password'] = array(
            'name' => 'password',
            'id' => 'password',
            'type' => 'password',
            'placeholder' => 'Heslo',
            'value' => $this->form_validation->set_value('passwordN'),
        );
        $data['password2'] = array(
            'name' => 'password2',
            'id' => 'password2',
            'type' => 'password',
            'placeholder' => 'Heslo',
            'value' => $this->form_validation->set_value('password2'),
        );

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->form_validation->set_rules('oldpass', 'Staré heslo', 'trim|required|min_length[4]|max_length[40]');
            $this->form_validation->set_rules('password', 'Nové heslo', 'trim|required|min_length[4]|max_length[40]');
            $this->form_validation->set_rules('password2', 'Kontrola hesla', 'trim|required|min_length[4]|max_length[40]');
            if ($this->form_validation->run() == false) {
                $data['error_message'] = 'Chyba v zadaných údajoch. Chyba pri validácii.';
            } else {
                $oldPassword = $this->input->post('oldpass');
                $oldPasswordHashed = hash('sha1', $oldPassword);
                $password = $this->input->post('password');
                $passwordHashed = hash('sha1', $password);
                $password2 = $this->input->post('password2');
                $userId = $this->user->getData()->id;
                $user = $this->AdminsModel->read($userId);
                if ($user->password != $oldPasswordHashed) {
                    $data['error_message'] = 'Zle zadané staré heslo.';
                } else {
                    if ($password != $password2) {
                        $data['error_message'] = 'Heslá sa nezhodujú.';
                    } else {
                        $o = new stdClass();
                        $o->id = $userId;
                        $o->password = $passwordHashed;
                        $this->AdminsModel->update($o);
                        $data['accept_message'] = 'Heslo bolo zmenené';
                    }
                }
            }
        }
        $this->load->view('templates/headers/header', $data, FALSE);
        $this->load->view('auth/pass_change', $data, FALSE);
        $this->load->view('templates/footers/footer', null, FALSE);
    }

    /**
     * 	Funkcia manažuje zmenu hesla pre pridávanie nových programov.
     * 
     * Administrátor musí pri zmene hesiel pre upload súborov zadať svoje prihlasovacie heslo a
     * dvakrát nové heslo aby sa mohla skontrólovať zhoda zadaných hesiel.
     */
    public function upload_pass_change() {
        if (!$this->user->isLogged()) {
            $data['error_message'] = 'Nie ste prihlásený!';
            $data['redirect_to'] = ''; // url , kde sa bude redirectovat '' home, inac napr 'programs_managment/index' inde
            $this->load->view('templates/headers/h_redirect_index', $data, FALSE);
            $this->load->view('auth/log_message', $data, FALSE);
            $this->load->view('templates/footers/footer', null, FALSE);
            return;
        }

        $data['title'] = 'Zmena hesla súboru';
        $data['adminpass'] = array(
            'name' => 'adminpass',
            'id' => 'adminpass',
            'type' => 'password',
            'placeholder' => 'Heslo',
            'value' => $this->form_validation->set_value('adminpass'),
        );
        $data['newpass'] = array(
            'name' => 'newpass',
            'id' => 'newpass',
            'type' => 'password',
            'placeholder' => 'Heslo',
            'value' => $this->form_validation->set_value('newpass'),
        );
        $data['newpass2'] = array(
            'name' => 'newpass2',
            'id' => 'newpass2',
            'type' => 'password',
            'placeholder' => 'Heslo',
            'value' => $this->form_validation->set_value('newpass2'),
        );

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->form_validation->set_rules('adminpass', 'Heslo admina', 'trim|required|min_length[4]|max_length[40]');
            $this->form_validation->set_rules('newpass', 'Nové heslo', 'trim|required|min_length[4]|max_length[40]');
            $this->form_validation->set_rules('newpass2', 'Nové heslo 2', 'trim|required|min_length[4]|max_length[40]');
            if ($this->form_validation->run() == false) {
                $data['error_message'] = 'Chyba v zadaných údajoch. Chyba pri validácii.';
            } else {
                $adminPassword = $this->input->post('adminpass');
                $adminPasswordHashed = hash('sha1', $adminPassword);
                $newPassword = $this->input->post('newpass');
                $newPasswordHashed = hash('sha1', $newPassword);
                $newPassword2 = $this->input->post('newpass2');
                $userId = $this->user->getData()->id;
                $user = $this->AdminsModel->read($userId);
                if ($user->password != $adminPasswordHashed) {
                    $data['error_message'] = 'Zle zadané staré heslo';
                } else {
                    if ($newPassword != $newPassword2) {
                        $data['error_message'] = 'Heslá sa nezhodujú';
                    } else {
                        $o = new stdClass();
                        $o->id = 1;
                        $o->password = $newPasswordHashed;
                        $this->PasswordModel->update($o);
                        $data['accept_message'] = 'Heslo bolo zmenené';
                    }
                }
            }
        }
        $this->load->view('templates/headers/header', $data, FALSE);
        $this->load->view('auth/upload_pass_change', $data, FALSE);
        $this->load->view('templates/footers/footer', null, FALSE);
    }

    /**
     * 	Funkcia slúži na verifikáciu ajaxových dotazov pre kontrou hesla.
     */
    public function check_password() {
        $this->load->model('passwordmodel');
        $data = 'dummy';



        if ($this->input->is_ajax_request()) {
            $data = $this->passwordmodel->check_password($this->input->post('heslo'));


            echo json_encode($data);
        } else {
            
        }
    }

    private function createSession($obj) {
        $sessObj = new stdClass();
        $sessObj->id = $obj->id;
        $sessObj->login = $obj->login;
        $sessObj->name = $obj->name;
        $sessObj->last_loggin = $obj->last_loggin;
        $this->user->setData($sessObj);
    }

    private function updateLastLogin($userID) {
        $o = new stdClass();
        $o->id = $userID;
        $o->last_loggin = date('Y-m-d H:i:s');
        $this->AdminsModel->update($o);
    }

}

/* End of file auth.php */
/* Location: ./application/controllers/auth.php */
 
